package com.atom.app.mvvm.ui.activities

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.input.getInputField
import com.afollestad.materialdialogs.input.input
import com.atom.app.mvvm.AppModel
import com.atom.app.mvvm.BR
import com.atom.app.mvvm.R
import com.atom.app.mvvm.VMFactory
import com.atom.app.mvvm.abase.BaseKingContainerActivity
import com.atom.app.mvvm.abase.BaseKingContainerViewModel
import com.atom.app.mvvm.Contacts
import com.atom.app.mvvm.databinding.ActivityMainBinding
import com.atom.app.mvvm.net.BaseResponse
import com.atom.app.mvvm.net.bean.AuthorResult
import com.atom.app.mvvm.net.bean.LoginResult
import com.atom.app.mvvm.net.dto.LoginUser
import com.atom.app.mvvm.ui.fragments.MainFragment
import com.atom.app.mvvm.ui.fragments.TaskFragment
import com.atom.app.mvvm.ui.fragments.UserFragment
import com.atom.app.mvvm.utils.JacksonUtils
import com.atom.module.logger.Logger
import com.atom.module.mvvm.adapter.ClickEvent
import com.atom.module.mvvm.util.Auto
import com.google.android.material.navigation.NavigationView
import com.tencent.mmkv.MMKV
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver
import io.reactivex.rxjava3.schedulers.Schedulers

class MainActivity : BaseKingContainerActivity<ActivityMainBinding, MainViewModel>(),
    NavigationView.OnNavigationItemSelectedListener {

    override fun initArgs(intent: Intent, savedInstanceState: Bundle?): Boolean {
        Auto.registerTask(MainViewModel::class) {
            loadFragment(TaskFragment())
            true
        }
        return super.initArgs(intent, savedInstanceState)
    }

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_main
    }

    override fun initContainerView(): Int {
        return R.id.frameLayout
    }

    override fun initVariableId(): Int {
        return BR.mainViewModel
    }

    override fun initViewModel(): MainViewModel {
        return ViewModelProvider(this, VMFactory).get(MainViewModel::class.java)
    }

    override fun initViewBinding(binding: ActivityMainBinding, viewModel: MainViewModel) {
        super.initViewBinding(binding, viewModel)
        val toolbar = findViewById<View>(R.id.toolbar) as Toolbar
        if (supportActionBar == null) {
            setSupportActionBar(toolbar)
        }
        toolbar.setNavigationOnClickListener {
            binding.drawLayout.openDrawer(GravityCompat.START)
        }
        binding.navLayout.setNavigationItemSelectedListener(this)
    }

    override fun initData(view: View) {
        super.initData(view)
        view.post {
            if (viewModel.isFirstLaunchApp()) {
                MaterialDialog(this).show {
                    title(text = "问卷调查系统")
                    message(
                        text = """
                    更新日志(V2.0.0):
                    1.完成App端用户管理功能;
                    更多功能即将上线,敬请期待!!!
                """.trimIndent()
                    )
                    positiveButton(text = "知道了") { dialog ->
                        dialog.dismiss()
                        // 打来默认的fragment
                        loadFragment(MainFragment::class.java, true)
                    }
                    negativeButton(text = "查询任务") { dialog ->
                        dialog.dismiss()

                        MaterialDialog(this@MainActivity).show {
                            input(allowEmpty = true, prefill = "赵芳宇")
                            positiveButton(text = "查询") { dialog ->
                                val inputField = dialog.getInputField()
                                var result = "赵芳宇"
                                inputField.text.toString().also {
                                    if (it.isNotEmpty()) {
                                        result = it
                                    }
                                }
                                loadFragment(TaskFragment().apply {
                                    this.arguments = Bundle().also {
                                        it.putString(Contacts.tag_username, result)
                                    }
                                })
                            }
                        }

                    }

                    setOnShowListener {
                        viewModel.setFirstLaunchApp()
                    }
                }
            } else {
                loadFragment(MainFragment::class.java, true)
            }
        }
    }

    @SuppressLint("CheckResult")
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_person -> {
                loadFragment(UserFragment())
            }
            R.id.nav_task -> {
                MaterialDialog(this).show {
                    input(allowEmpty = true, prefill = "赵芳宇")
                    positiveButton(text = "查询") { dialog ->
                        val inputField = dialog.getInputField()
                        var result = "赵芳宇"
                        inputField.text.toString().also {
                            if (it.isNotEmpty()) {
                                result = it
                            }
                        }
                        loadFragment(TaskFragment().apply {
                            this.arguments = Bundle().also {
                                it.putString(Contacts.tag_username, result)
                            }
                        })
                    }
                }
            }
            R.id.nav_set -> {
                toastShow(getString(R.string.please_wait))
                // 进行测试access/refresh token
                viewModel.listAUthor()
            }
            R.id.nav_report -> {
                toastShow(getString(R.string.please_wait))
            }
            R.id.nav_logout -> {
                MMKV.defaultMMKV().encode(Contacts.tag_is_login, false)
                startActivity(LoginActivity::class.java)
                finish()
            }
        }
        toastShow(item.title.toString())
        binding.drawLayout.closeDrawer(GravityCompat.START)
        return true
    }
}


open class MainViewModel : BaseKingContainerViewModel<AppModel>(AppModel) {

    fun isFirstLaunchApp(): Boolean {
        return model.mmkv.decodeBool(Contacts.tag_is_first)
    }

    fun setFirstLaunchApp() {
        model.mmkv.encode(Contacts.tag_is_first, true)
    }

    fun listAUthor(){
        addSubscribe(
            model.netApi.listAuthor()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(object : BlockingBaseObserver<BaseResponse<List<AuthorResult>>>() {
                    override fun onNext(t: BaseResponse<List<AuthorResult>>) {
                        Logger.i(JacksonUtils.objectMapper.writeValueAsString(t))
                    }

                    override fun onError(e: Throwable) {
                        Logger.e(e)
                    }
                })
        )
    }

    val onclick = object : ClickEvent() {
        override fun invoke(t: View) {
//            startActivity(CameraActivity::class.java)
//            startActivity(DrawActivity::class.java)
//            MMKV.defaultMMKV().encode(Contacts.tag_is_first, false)
        }
    }
}
